<template>
  <div>
    <!-- 面包屑导航区-->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片视图区-->
    <el-card>
      <!--      警告去-->
      <el-alert
        title="注意:只能给三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      <!--    商品分类区域-->
      <el-row class="category">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            :options="cateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            clearable
            @change="cateListChanged">
          </el-cascader>
        </el-col>
        
      </el-row>
<!--      tab栏-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">动态参数</el-button>
          <el-table
            :data="manyParmasData"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @click="handle(i,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
             <template slot-scope="scope">
               <el-button icon="el-icon-edit" type="primary" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
               <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
             </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">静态属性</el-button>
          <el-table
            :data="onlyParamsData"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
<!--      添加参数对话框-->
      <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%">
        <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改参数对话框-->
      <el-dialog
        :title="'修改'+titleText"
        :visible.sync="editParamsDialogVisible"
        width="50%">
        <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
   
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      //获取的分类数据列表
      cateList: [],
      cascaderProps:{
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true // 是否遵守父子组件之间不关联
      },
      selectedKeys: [], //存放已选中的id,
      activeName: 'many', //指定当前选择项
      manyParmasData: [], //动态参数列表
      onlyParamsData: [], //静态属性列表
      addParamsDialogVisible: false, //添加参数对话框
      addParamsForm: {
        attr_name: ''
      }, //添加参数表格
      //规则验证
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      editParamsDialogVisible: false, //修改参数对话框
      //修改参数表单
      editParamsForm: {
      
      },
      editParamsFormRules:{
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      inputVisible: false, // 文本框显示与隐藏
      inputValue: '' //文本框的值
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      let { data: res } = await this.$http.get(`categories`, { params: { type: 3 } })
      this.cateList = res.data
      // console.log(this.cateList)
    },
    //级联选择器改变时触发
    async cateListChanged () {
      this.getParams()
    },
    //定义一个获取参数的函数
    async getParams () {
      //如果没有选中三级分类,清空
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyParmasData = []
        this.onlyParamsData = []
        return
      }
      //发送请求,获取动态参数数据
      let { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      // console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyParmasData = res.data
      } else if (this.activeName === 'only') {
        this.onlyParamsData = res.data
      }
    },
    //tab切换时触发
    handleClick() {
      // console.log(this.activeName)
      this.getParams()
    },
    //添加参数对话框
    addParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addParamsDialogVisible = false
        this.getParams()
      })
    },
    showAddParamsDialog() {
      this.addParamsDialogVisible = true
      this.getParams()
    },
    //展示修改功能对话框
    async showEditDialog(id) {
      this.editParamsDialogVisible = true
      let { data : res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('查询参数失败')
      // console.log(res)
      this.editParamsForm = res.data
    },
    //修改参数
    // eslint-disable-next-line camelcase
    editParams() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        let { data : res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getParams()
        this.editParamsDialogVisible = false
      })
    },
    //删除参数
    async deleteParams (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 用户取消了删除的操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      let { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      this.getParams()
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      //如果没有return,说明用户输入的是正确的数据,执行下一步操作
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      //发送ajax请求
      let { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加参数失败')
      this.$message.success('添加参数成功')
    },
    //点击按钮让输入框显示
    showInput(row) {
      row.inputVisible = true
      //自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed:{
    // 用来监听按钮是否被选中
    isBtnDisabled() {
      return this.selectedKeys.length !== 3
    },
    //获取三级分类id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    //获取添加参数对话框标题
    // eslint-disable-next-line vue/return-in-computed-property
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else if (this.activeName === 'only') {
        return '静态属性'
      }
    }
  }
}
</script>

<style scoped lang="less">
.category{
  margin-top: 15px;
  font-size: 14px;
  span{
    margin-right: 10px;
  }
}
  .input-new-tag{
    width: 130px;
    margin-top: 10px;
  }
</style>
